package com.gamota.mobi.background;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.view.View;

import com.easy.facebook.android.data.Person;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.event.Exception;
import com.gamota.mobi.event.Event.GoogleTokenEvent;
import com.gamota.mobi.model.AppStoreVnApplicationInfo;
import com.gamota.mobi.model.ContentItemInfo;
import com.gamota.mobi.model.UserInfo;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class BackgroundTasks {

	private static ContentNetworkInterface cni;
	private EventBus eventBus;
	private Context context;
	private static String googleToken;
	
	public BackgroundTasks(Context context){
		this.context = context;
		eventBus = EventBus.getDefault();
		cni = ContentNetworkInterface.getInstance().init(context);
	}
	
	public static class GetFBFriendsEvent {
		public List<Person> getList() {
			return list;
		}
		List<Person> list;

		public GetFBFriendsEvent(List<Person> list) {
			this.list = list;
		}
		
	}
	
	public void convertLink(String accessToken, String link){
		cni.convertLink(accessToken, link);
	}
	
	public void getRequestToken(){
		List<String> scopes = new ArrayList<String>();
		scopes.add(Constants.INAPP_SCOPE);
		try {
			cni.getRequestToken(Constants.RESPONSE_TYPE, Constants.CLIENT_KEY, Constants.DEFAULT_REDIRECT_URI, scopes, Constants.STATE, Constants.LANG);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void checkRemainGift(String accessToken, String slug){
		cni.checkRemainGift(accessToken, slug);
	}
	
	public void getTopContent(String type, int cateId, String accessToken, int storeId, int start){
		cni.getTopContent(type, cateId, accessToken, storeId, start);
	}
	
	public void getAccessToken(final String requestToken){
		cni.getAccessToken(requestToken, Constants.CLIENT_KEY, Constants.CLIENT_SECRET, Constants.DEFAULT_REDIRECT_URI, Constants.GRANT_TYPE, Constants.LANG);
	}
	
	public void refreshToken(final String accessToken){
		cni.refreshToken(accessToken, Constants.CLIENT_KEY, Constants.CLIENT_SECRET);
	}
	
	public void getUserInfo(final String accessToken){
		cni.getUserInfo(accessToken);
	}
	
	public void logIn(final String accessToken, final String username, final String password){
		cni.login(context, accessToken, username, password);
	}
	
	public void googleLogIn(String accessToken, String googleToken, String email){
		cni.loginGoogle(accessToken, googleToken, email);
	}
	
	public void registerGoogle(String accessToken, String googleToken, String username, String password){
		cni.registerGoogle(accessToken, googleToken, username, password);
	}
	
	public void registerFacebook(String accessToken, String facebookToken, String username, String password){
		cni.registerFacebook(accessToken, facebookToken, username, password);
	}
	
	public void loginFacebook(String accessToken, String facebookToken, String facebookEmail){
		cni.loginFacebook(accessToken, facebookToken, facebookEmail);
	}
	
	public void logOut(final String accessToken){
		cni.logout(accessToken);
	}
	
	public void checkVersionBought(String type, String accessToken, View v, MenuItem item){
		cni.checkVersionBought(type, accessToken, v, item);
	}
	
	public void checkClientUpdate(final String isRooted){
				String deviceId = Utils.getDeviceId(context);
				PackageManager pm = context.getPackageManager();
				String version = "";
				int build = 0;
				try {
					PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
					version = pi.versionName;
					build = pi.versionCode;
					cni.checkAppStoreVnUpdate(Constants.UPDATE_CLIENT, deviceId, version, String.valueOf(build), isRooted);
				} catch (NameNotFoundException e) {
					e.printStackTrace();
					eventBus.post(new Event.ClientUpdateNameNotFoundEvent());
				}
	}
	
	public void checkUpdateContent(String accessToken, String type, int start, int limit, String store, String packageNameList, boolean show){
		cni.checkContentUpdate(accessToken, type, start, limit, store, packageNameList, show);
	}
	
	public void getCategories(String accessToken, int storeId, String type){
		cni.getCategoryList(accessToken, storeId, type);
	}
	
	public void getAllBanners(String accessToken, String store, String page, String where){
		cni.getAllBanners(accessToken, store, page, where);
	}
	
	public void getTextBanners(String accessToken, String store, String where){
		cni.getTextBanners(accessToken, store, where);
	}
	
	public void getBannerByPage(final String accessToken, final String store, final String page){
		cni.getBannerByPage(accessToken, store, page);
	}
	
	public void register(final String accessToken, final String username, final String password, final String email){
		cni.register(context, accessToken, username, password, email);
	}
	
	public void exchangeTYM(final String accessToken, final String tym){
		cni.exchangeTYM(accessToken, tym);
	}
	
	public void giftcode(final String username, final String giftCode){
		cni.giftcode(username, giftCode);
	}
	
	public void buyContent(String topType, String accessToken, String appId, long versionId){
		cni.buy(topType, accessToken, appId, versionId);
	}
	
	public void buyAttachedContent(String accessToken, String appId, int versionId){
		cni.buyAttached("attach", accessToken, appId, versionId);
	}
	
	public void getAttachedDownloadLink(String topType, String accessToken, String appId, long versionId, boolean isRooted, String referer){
		cni.getAttchedDownloadLink(topType, accessToken, appId, versionId, isRooted, referer, false);
	}
	
	public void buyMultipleContent(final String accessToken, final List<AppStoreVnApplicationInfo> appIdList){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.buyMultiple(accessToken, appIdList);
			}
		});
	}
	
	public void getMultipleDownloadLink(final String accessToken, final List<AppStoreVnApplicationInfo> appIdList, final boolean isRooted, final String referer){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.getMultipleDownloadLink(accessToken, appIdList, isRooted, referer);
			}
		});
	}
	
	public void buyMultipleContentCollection(final String accessToken, final List<ContentItemInfo> appIdList){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.buyMultipleContent(accessToken, appIdList);
			}
		});
	}
	
	public void getMultipleContentDownloadLink(final String accessToken, final List<ContentItemInfo> appIdList, final boolean isRooted, final String referer){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.getMultipleContentDownloadLink(accessToken, appIdList, isRooted, referer);
			}
		});
	}
	
	public void getGoogleToken(final Activity activity, final String account, final String scopes) {
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				final GoogleTokenEvent event = new GoogleTokenEvent();
				try {
					//String googleToken = GoogleAuthUtil.getTokenWithNotification(activity, account, scopes, null, makeCallback());
					String googleToken = GoogleAuthUtil.getToken(activity, account, scopes);
					event.setGoogleToken(googleToken);
					EventBus.getDefault().post(event);
				} catch (IOException e) {
					EventBus.getDefault().post(new Exception.GetGoogleTokenIOException());
					e.printStackTrace();
				} catch (GoogleAuthException e) {
					e.printStackTrace();
					EventBus.getDefault().post(new Exception.GetGoogleTokenException());
				}
			}
		});
	}

	public void getFullItemInfo(String accessToken, String slug, String packageName, String referer){
		cni.getFullItemInfo(accessToken, slug, packageName, referer);
	}
	
	public void getVersionList(String accessToken, String slug, String topType){
		cni.getVersionList(accessToken, slug, topType);
	}

	public static void callGoogleApi(final String googleToken) {
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				try {
					UserInfo user = cni.callGoogleApi(googleToken);
					EventBus.getDefault().post(new Event.CallGoogleAPISuccessEvent(user));
				} catch (IOException e) {
					EventBus.getDefault().post(new Exception.GoogleApiIOException());
					e.printStackTrace();
				} catch (InterruptedException e) {
					EventBus.getDefault().post(new Exception.GoogleApiInterruptException());
					e.printStackTrace();
				}
			}
		});
	}
	
//	public void getFeedList(final String store, final int start, final int limit){
//		cni.getFeedList(store, start, limit);
//	}
	
	public void getFBFeedList(int limit){
		cni.getFBFeedList(limit);
	}
	
	public void getFeedComments(String id, int limit){
		cni.getFeedComments(id, limit);
	}
	
	public void getFeedLikes(String objectId){
		cni.getFeedDetailsLikes(objectId);
	}
	
	public void getCollectionGroup(final String accessToken, final String store){
		cni.getCollectionGroup(accessToken, store);
	}
	
	public void getLevel2CollectionList(String accessToken, String store, int groupId){
		cni.getLevel2CollectionList(accessToken, store, groupId);
	}
	
	public void getLevel3CollectionList(String accessToken, String store, int listId){
		cni.getLevel3CollectionList(accessToken, store, listId);
	}
	
	public void getCollectionContent(String accessToken, int collectionId, String filter){
		cni.getCollectionContent(accessToken, collectionId, filter);
	}
	
	public void getAllCollections(final String json){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.getAllCollections(json);
			}
		});
	}
	
	public void getHotItemByCateId(String topType, String accessToken, int storeId, int categoryId, int start){
		cni.getHotByCatId(topType, accessToken, storeId, categoryId, start);
	}
	
	public void clickBanner(String url){
		cni.clickBanner(url);
	}
	
	public void getComments(String accessToken, String appId, int start){
		cni.getComments(accessToken, appId, start);
	}
	
	public void buyTYMSMS(String from, String accessToken){
		cni.buyTYMViaSMS(from, accessToken);
	}
	
	public void buyTYMCard(String from, String accessToken, String cardSerial, String cardCode, String vendor){
		cni.buyTYMViaCard(from, accessToken, cardSerial, cardCode, vendor);
	}
	
	public void buyTYMBank(String accessToken, String amount){
		cni.buyTYMViaBank(accessToken, amount);
	}
	
	public void buyTYMPaypal(String accessToken, String amount){
		cni.buyTYMViaPaypal(accessToken, amount);
	}
	
//	public void checkTopupResult(final String accessToken, final String topupId){
//		AsyncExecutor.create().execute(new RunnableEx() {
//			@Override
//			public void run() throws java.lang.Exception {
//				cni.checkTopup(accessToken, topupId);
//			}
//		});
//	}
	
	public void watchMovie(String topType, String accessToken, String appId, long versionId, boolean isRooted, String referer){
		cni.getDownloadLink(topType, accessToken, appId, versionId, isRooted, referer, true);
	}
	
	public void getDownloadLink(String topType, String accessToken, String appId, long versionId, boolean isRooted, String referer){
		cni.getDownloadLink(topType, accessToken, appId, versionId, isRooted, referer, false);
	}
	
	public void sendComment(String accessToken, String appId, String comment){
		cni.writeComment(accessToken, appId, comment);
	}
	
	public void rate(String accessToken, String appId, float score){
		cni.rate(accessToken, appId, score);
	}
	
	public void getHotKeywords(String accessToken, String store, String limit){
		cni.getHotKeywords(accessToken, store, limit);
	}
	
	public void getRecommendItems(String accessToken, String store, String start, String limit){
		cni.getRecommentItem(accessToken, store, start, limit);
	}
	
	public void searchAll(String accessToken, int storeId, String keyword, int start){
		cni.searchAll(accessToken, storeId, keyword, start);
	}
	
	public void search(String accessToken, int storeId, String keyword, int start){
		cni.search(accessToken, storeId, keyword, start);
	}
	
	public void registerGCM(String accessToken, String regId, String allowPush, boolean isRooted, int lastNotificationId) throws NameNotFoundException{
		cni.registerDevice(context, accessToken, regId, allowPush, isRooted, lastNotificationId);
	}
	
	public void unregisterGCM(String regId){
		cni.unregister(context, regId);
	}
	
	public void changePassword(String accessToken, String oldPassword, String newPassword){
		cni.changePassword(accessToken, oldPassword, newPassword);
	}
	
	public void getTransactionLog(String accessToken, int start){
		cni.getUserTransactions(accessToken, start);
	}
	
	public void getDownloadHistory(String accessToken, int storeId){
		cni.getDownloadedList(accessToken, storeId);
	}
	
	public void createUserSetting(String accessToken, String settingName, String content, int permission){
		cni.createUserSettings(accessToken, settingName, content, permission);
	}
	
	public void updateUserSetting(String accessToken, String settingName, String content, int permission){
		cni.updateUserSetting(accessToken, settingName, content, permission);
	}
	
	public void getSettingList(String accessToken){
		cni.getUsetSettingList(accessToken);
	}
	
	public void getSettingDetails(String accessToken, String settingName, String key){
		cni.getSettingDetails(accessToken, settingName, key);
	}
	
	public void getAllSettingDetails(final String accessToken, final List<String> nameList){
		AsyncExecutor.create().execute(new RunnableEx() {
			
			@Override
			public void run() throws java.lang.Exception {
				// TODO Auto-generated method stub
				cni.getAllSettingDetails(accessToken, nameList);
			}
		});
	}
	
	public void getGiftboxList(String accessToken){
		cni.getUserGiftboxList(accessToken);
	}
	
	public void openGiftbox(String accessToken, int giftboxId){
		cni.openGiftbox(accessToken, giftboxId);
	}
	
	public void buyGift(String accessToken, int itemId){
		cni.buyGift(accessToken, itemId);
	}
	
	public void reportInstall(String accessToken, String slug, int versionId, String status){
		cni.reportInstall(accessToken, slug, versionId, status);
	}
	
	public void reportGiftbox(String accessToken, String slug, String type, String packageName){
		cni.reportGiftbox(accessToken, slug, type, packageName);
	}
	
	public void like(String accessToken, String objectId){
		cni.like(accessToken, objectId);
	}
	
	public void unlike(String accessToken, String objectId){
		cni.unlike(accessToken, objectId);
	}
	
	public void commentFB(String accessToken, String objectId, String message){
		cni.commentFB(accessToken, objectId, message);
	}
	
	public void getLikeNumber(String url){
		cni.getNumberOfLikes(url);
	}
	
	public void likedOrNot(String url, String facebookToken){
		cni.likedOrNot(url, facebookToken);
	}
	
	private Intent makeCallback() {
		Intent intent = new Intent();
		intent.setAction("com.gamota.mobi.oauth2.Callback");
		return intent;
	}

	/**
	 * Note: Make sure that the receiver can be called from outside the app. You
	 * can do that by adding android:exported="true" in the manifest file.
	 */
	public static class CallbackReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent callback) {
			callGoogleApi(googleToken);
		}
	}
}
